<?php

namespace app\admin\controller\customer;

use app\admin\model\cost\Expenses;
use app\common\controller\Backend;
use Endroid\QrCode\QrCode;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 服务内容
 *
 * @icon fa fa-circle-o
 */
class Intention extends Backend
{
    protected $dataLimit = 'auth'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id';

    /**
     * Intention模型对象
     * @var \app\admin\model\customer\Intention
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\customer\Intention;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignconfig('fuwuliebiao', $this->auth->check('customer/package/index'));
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $service_list = Db::name('service')->select();
            $this->assignconfig('service', $service_list);
            return $this->view->fetch('', ['service' => $service_list]);
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if ($params['customer_identity'] == 0) {
                $params['signatory'] = $params['full_name'];
            }


            $result = $this->model->allowField(true)->save($params);

            $packageModel = new \app\admin\model\customer\Package();
            $packageModel->save([
                'customer_id' => $this->model->id,
                'admin_id' => $this->auth->id,
                'service_desc' => $params['service_desc'],
                'pay_type' => $params['pay_type'],
                'create_time' => time()
            ]);


            $serviceData = [];
//            if (!empty($params['serviceTable'])) {
//                foreach ($params['serviceTable'] as $item) {
//                    $serviceData[] = [
//                        'package_id' => $packageModel->package_id,
//                        'customer_id' => $this->model->id,
//                        'service_id' => $item['service_id'],
//                        'service_name' => $item['service_name'],
//                        'ledger_expenses' => $item['ledger_expenses'],
//                        'corporate_type' => $item['corporate_type'],
//                        'standard_price' => $item['standard_price'],
//                        'cost_price' => $item['cost_price'],
//                        'deal_price' => $item['deal_price'],
//                        'collection_price' => $item['collection_price'],
//                        'balance_price' => $item['balance_price'],
//                        'month' => $item['month'],
//                        'start_time' => time(),
//                        'end_time' => strtotime("+{$item['month']} month"),
//                    ];
//                }
//            }
            if (!empty($params['serviceTable'])) {
                (new \app\admin\model\customer\Service)->where(['package_id' => $packageModel->package_id])->delete();
                foreach ($params['serviceTable'] as $item) {
                    $service = \app\admin\model\Service::get($item['service_id'])->toArray();
                    if (!$service) {
                        continue;
                    }
                    $types = [
                        'gth', 'xgmnsr', 'ybnsr'
                    ];
                    $orporate_type = $item['corporate_type'];

                    //成本
                    $cost_type = $service[$types[$orporate_type] . '_cost_type'];
                    $cost_value = $service[$types[$orporate_type] . '_cost_value'];
                    if ($cost_type == 0) {
                        $cost_value = $item['collection_price'] * getPercentage($cost_value);
                    } else if ($cost_type == 1) {
//                        $cost_value = $cost_value;
                    } else if ($cost_type == 2) {
                        $cost_value = json_decode($cost_value, true);
                        $cost_value = (new Expenses())->where('id', 'in', $cost_value)->sum('price');
                    }

                    // 会计
                    $account_commission_type = $service[$types[$orporate_type] . '_commission_account_type'];
                    $commission_account = $service[$types[$orporate_type] . '_commission_account'];
                    $account_commission = 0;
                    if ($account_commission_type == 0) {
                        $account_commission = $item['collection_price'] * getPercentage($commission_account);
                    } else {
                        $account_commission = $commission_account;
                    }

                    // 销售
                    $sales_commission_type = $service[$types[$orporate_type] . '_commission_sales_type'];
                    $commission_sales = $service[$types[$orporate_type] . '_commission_sales'];
                    $sales_commission = 0;
                    if ($sales_commission_type == 0) {
                        $sales_commission = ($item['collection_price'] - $cost_value) * getPercentage($commission_sales);
                    } else {
                        $sales_commission = $commission_account;
                    }

                    //外勤
                    $outworker_commission_type = $service[$types[$orporate_type] . '_commission_outworker_type'];
                    $commission_outworker = $service[$types[$orporate_type] . '_commission_outworker'];
                    $outworker_commission = 0;
                    if ($outworker_commission_type == 0) {
                        $outworker_commission = $item['collection_price'] * getPercentage($commission_outworker);
                    } else {
                        $outworker_commission = $commission_outworker;
                    }

                    $serviceData[] = [
                        'package_id' => $packageModel->package_id,
                        'customer_id' => $this->model->id,
                        'service_id' => $item['service_id'],
                        'service_name' => $item['service_name'],
                        'ledger_expenses' => $item['ledger_expenses'],
                        'corporate_type' => $item['corporate_type'],
                        'standard_price' => $item['standard_price'],
                        'deal_price' => $item['deal_price'],
                        'collection_price' => $item['collection_price'],
                        'balance_price' => $item['balance_price'],

                        //成本价格
                        'cost_type' => $cost_type,
                        'cost_price' => $cost_value,

                        //提成计算
                        'account_commission_type' => $account_commission_type,
                        'account_commission' => $account_commission,
                        'sales_commission_type' => $sales_commission_type,
                        'sales_commission' => $sales_commission,
                        'outworker_commission_type' => $outworker_commission_type,
                        'outworker_commission' => $outworker_commission,

                        //服务期限
                        'month' => $item['month'],
//                        'start_time' => $item['month'] ? time() : 0,
//                        'end_time' => $item['month'] ? strtotime("+{$item['month']} month") : 0,
                    ];
                }
            }

            $result2 = (new \app\admin\model\customer\Service)->allowField(true)->saveAll($serviceData);

            //生成合同
            $packageModel->generateContract();

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false || $result2 === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if ($params['customer_identity'] == 0) {
                $params['signatory'] = $params['full_name'];
            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function previewcontract($ids)
    {
        $customer = $this->model::get($ids);
        if (!$customer) {
            return false;
        }
        $url = 'https://view.officeapps.live.com/op/view.aspx?src=https://crm.szhxvip.com/' . $customer->contract_url;
        header("Location: $url");
        exit();
    }

    public function signatureQrcode($ids)
    {
        $qrCode = new QrCode('https://crm.szhxvip.com/index/index/signature?customer_id=' . $ids);
        $dataUri = $qrCode->writeDataUri();
        echo '<div style="height: calc(100vh - 40px);display: flex;justify-content: center;align-items: center"><div style="text-align: center"><span style="font-size: 23px;font-weight: bold">三众合信财税电子合同</span><br><img style="width:240px;height: 240px;margin-bottom: 10px" src="' . $dataUri . '"><br>请使用手机扫描上方二维码完成签订</div></div>';
        die;
    }

    public function deal($ids)
    {
        $customer = $this->model::get($ids);
        if (!$customer) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            $params['customer_type'] = 1;
            $result = $customer->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
